<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="90px">
      <el-row>
        <el-col :span="15">
          <el-form-item label="主题" prop="name">
            <el-input v-model="dataForm.name" placeholder="主题名称"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <!--      <el-row>-->
      <!--        <el-col :span="15">-->
      <!--          <el-form-item label="价格:" prop="price">-->
      <!--            <el-input v-model="dataForm.price" placeholder="0.00，单位为：元"></el-input>-->
      <!--          </el-form-item>-->
      <!--        </el-col>-->
      <!--      </el-row>-->
      <el-row>
        <el-col :span="15">
          <el-form-item label="缩略图:" prop="thumb">
            <div class="myhead">
              <el-tooltip content="点击上传缩略图" placement="top">
                <el-image  style="width: 90px; height: 60px" :src="dataForm.thumb" fit="contain" @click="uploadThumbHandle()" alt=""/>
              </el-tooltip>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="详情图1:" prop="image1">
            <div class="myhead">
              <el-tooltip content="点击上传详情图1" placement="top">
                <el-image  style="width: 90px; height: 60px" :src="dataForm.image1" fit="contain" @click="uploadImage1Handle()" alt=""/>
              </el-tooltip>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="详情图2:" prop="image2">
            <div class="myhead">
              <el-tooltip content="点击上传详情图2" placement="top">
                <el-image  style="width: 90px; height: 60px" :src="dataForm.image2" fit="contain" @click="uploadImage2Handle()" alt=""/>
              </el-tooltip>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="锁屏壁纸:" prop="screen">
            <div class="myhead">
              <el-tooltip content="点击上传锁屏壁纸" placement="top">
                <el-image  style="width: 90px; height: 60px" :src="dataForm.screen" fit="contain" @click="uploadScreenHandle()" alt=""/>
              </el-tooltip>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="桌面壁纸:" prop="desktop">
            <div class="myhead">
              <el-tooltip content="点击上传桌面壁纸" placement="top">
                <el-image  style="width: 90px; height: 60px" :src="dataForm.desktop" fit="contain" @click="uploadDesktopHandle()" alt=""/>
              </el-tooltip>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="主题附件:" prop="fileUrl">
            <div class="myhead">
              <el-tooltip content="点击上传图标ZIP文件附件" placement="top">
                <el-image style="width: 80px; height: 50px" :src="dataForm.attachmentpic" fit="contain" @click="uploadAttachment()" alt=""/>
              </el-tooltip>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="附件名:" prop="fileUrl">
            <div class="text item">
              {{dataForm.fileName}}
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="15">
          <el-form-item label="归类:" prop="classifyId">
            <el-select v-model="dataForm.classifyId" filterable placeholder="请选择所属分类类" size="medium" @change="onSelectType">
              <el-option v-for="item in itemsCatList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="15">
          <el-form-item label="描述:" prop="describes">
            <el-input
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 3}"
              placeholder="主题描述"
              v-model="dataForm.describes">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
    <!-- 弹窗, 上传缩略图 -->
    <theme-upload-thumb v-if="uploadThumbVisible" ref="themeUploadPic" @refreshDataList="refreshUploadThumb"></theme-upload-thumb>
    <!-- 弹窗, 上传详情图1 -->
    <theme-upload-image1 v-if="uploadImage1Visible" ref="themeUploadImage1" @refreshDataList="refreshUploadImage1"></theme-upload-image1>
    <!-- 弹窗, 上传详情图2 -->
    <theme-upload-image2 v-if="uploadImage2Visible" ref="themeUploadImage2" @refreshDataList="refreshUploadImage2"></theme-upload-image2>
    <!-- 弹窗, 上传详情图2 -->
    <theme-upload-screen v-if="uploadScreenVisible" ref="themeUploadScreen" @refreshDataList="refreshUploadScreen"></theme-upload-screen>
    <!-- 弹窗, 上传详情图2 -->
    <theme-upload-desktop v-if="uploadDesktopVisible" ref="themeUploadDesktop" @refreshDataList="refreshUploadDesktop"></theme-upload-desktop>
    <!-- 弹窗, 上传附件 -->
    <theme-upload-attachment v-if="uploadAttachmentVisible" ref="themeUploadAttachment" @refreshDataList="refreshAttachmentUrl"></theme-upload-attachment>
  </el-dialog>
</template>

<script>
  import 'babel-polyfill'
  // 上传缩略图
  import ThemeUploadThumb from './theme-upload-image'

  // 上传详情图1
  import ThemeUploadImage1 from './theme-upload-image'

  // 上传详情图2
  import ThemeUploadImage2 from './theme-upload-image'

  // 上传锁屏壁纸
  import ThemeUploadScreen from './theme-upload-image'

  // 上传详桌面壁纸
  import ThemeUploadDesktop from './theme-upload-image'

  // 上传附件
  import ThemeUploadAttachment from './theme-upload-attachment'

  export default {
    data () {
      return {
        visible: false,
        itemsCatList: [],
        uploadThumbVisible: false,
        uploadImage1Visible: false,
        uploadImage2Visible: false,
        uploadScreenVisible: false,
        uploadDesktopVisible: false,
        uploadAttachmentVisible: false,
        dataForm: {
          id: 0,
          name: '',
          price: '',
          classifyId: '',
          classifyName: '',
          describes: '',
          status: '',
          thumb: 'http://file-cdn-theme.cykonhy.com/default/default.jpg',
          image1: 'http://file-cdn-theme.cykonhy.com/default/default.jpg',
          image2: 'http://file-cdn-theme.cykonhy.com/default/default.jpg',
          screen: 'http://file-cdn-theme.cykonhy.com/default/default.jpg',
          desktop: 'http://file-cdn-theme.cykonhy.com/default/default.jpg',
          attachmentpic: 'http://file-cdn-theme.cykonhy.com/default/attachment.jpg',
          fileName:'',
          fileUrl: '',
        },
        dataRule: {
          name: [
            { required: true, message: '名称不能为空', trigger: 'blur' }
          ],
          classifyId: [
            { required: true, message: '分类Id不能为空', trigger: 'blur' }
          ],
          describes: [
            { required: true, message: '描述不能为空', trigger: 'blur' }
          ],
        }
      }
    },
    components: {
      ThemeUploadThumb,
      ThemeUploadImage1,
      ThemeUploadImage2,
      ThemeUploadScreen,
      ThemeUploadDesktop,
      ThemeUploadAttachment
    },
    methods: {
      init (id) {
        this.dataForm.id = id || 0
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/theme/theme-list/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.userId = data.theme.userId
                this.dataForm.name = data.theme.name
                // this.dataForm.price = this.regFenToYuan(data.theme.price)
                this.dataForm.classifyId = data.theme.classifyId
                this.dataForm.classifyName = data.theme.classifyName
                this.dataForm.thumb = data.theme.thumb
                this.dataForm.image1 = data.theme.image1
                this.dataForm.image2 = data.theme.image2
                this.dataForm.screen = data.theme.screen
                this.dataForm.desktop = data.theme.desktop
                this.dataForm.fileName = data.theme.fileName
                this.dataForm.fileUrl = data.theme.fileUrl
                this.dataForm.describes = data.theme.describes
                this.dataForm.status = data.theme.status
                this.dataForm.created = data.theme.created
                this.dataForm.updated = data.theme.updated
              }
            })
          }
        })
        this.initItemCat()
      },
      initItemCat () {
        this.$http({
          url: this.$http.adornUrl('/theme/theme-classify/list'),
          method: 'get',
          params: this.$http.adornParams({
            'page': 1,
            'limit': 10000
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.itemsCatList = data.page.list
          }
        })
      },
      // 筛选类型
      onSelectType (val) {
        let obj = this.itemsCatList.find((item) => {
          return item.id === val;
        });
        this.dataForm.classifyName = obj.name
      },
      // 上传缩略图
      uploadThumbHandle () {
        this.uploadThumbVisible = true
        this.$nextTick(() => {
          this.$refs.themeUploadPic.init()
        })
      },
      refreshUploadThumb (filePath) {
        this.dataForm.thumb = filePath
        this.uploadThumbVisible = false
      },

      // 上传详情图1
      uploadImage1Handle () {
        this.uploadImage1Visible = true
        this.$nextTick(() => {
          this.$refs.themeUploadImage1.init()
        })
      },
      refreshUploadImage1 (filePath) {
        this.dataForm.image1 = filePath
        this.uploadImage1Visible = false
      },

      // 上传详情图2
      uploadImage2Handle () {
        this.uploadImage2Visible = true
        this.$nextTick(() => {
          this.$refs.themeUploadImage2.init()
        })
      },
      refreshUploadImage2 (filePath) {
        this.dataForm.image2 = filePath
        this.uploadImage2Visible = false
      },

      // 上传锁屏壁纸
      uploadScreenHandle () {
        this.uploadScreenVisible = true
        this.$nextTick(() => {
          this.$refs.themeUploadScreen.init()
        })
      },
      refreshUploadScreen (filePath) {
        this.dataForm.screen = filePath
        this.uploadScreenVisible = false
      },

      // 上传锁桌面壁纸
      uploadDesktopHandle () {
        this.uploadDesktopVisible = true
        this.$nextTick(() => {
          this.$refs.themeUploadDesktop.init()
        })
      },
      refreshUploadDesktop (filePath) {
        this.dataForm.desktop = filePath
        this.uploadDesktopVisible = false
      },

      // 上传附件
      uploadAttachment () {
        this.uploadAttachmentVisible = true
        this.$nextTick(() => {
          this.$refs.themeUploadAttachment.init()
        })
      },
      refreshAttachmentUrl (fileList) {
        if (fileList.length > 0){
          this.dataForm.fileName = fileList[0].name
          this.dataForm.fileUrl = fileList[0].url
        }
        this.uploadAttachmentVisible = false
      },

      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            let itemPrice = this.regYuanToFen(this.dataForm.price,100)
            this.$http({
              url: this.$http.adornUrl(`/theme/theme-list/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'userId': this.dataForm.userId,
                'name': this.dataForm.name,
                // 'price': itemPrice,
                'classifyId': this.dataForm.classifyId,
                'classifyName': this.dataForm.classifyName,
                'thumb': this.dataForm.thumb,
                'image1': this.dataForm.image1,
                'image2': this.dataForm.image2,
                'screen': this.dataForm.screen,
                'desktop': this.dataForm.desktop,
                'fileName': this.dataForm.fileName,
                'fileUrl': this.dataForm.fileUrl,
                'describes': this.dataForm.describes,
                'status': this.dataForm.status,
                'created': this.dataForm.created,
                'updated': this.dataForm.updated
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      /**
       * 分转化为元 - 正则解决精度
       * @param fen
       * @returns {boolean|string}
       */
      regFenToYuan (fen) {
        var num = fen
        num = fen * 0.01
        num += ''
        var reg = num.indexOf('.') > -1 ? /(\d{1,3})(?=(?:\d{3})+\.)/g : /(\d{1,3})(?=(?:\d{3})+$)/g
        num = num.replace(reg, '$1')
        num = this.toDecimal2(num)
        return num
      },
      /**
       * 元转分 - 解决精度问题 yuan:要转换的钱，单位元； digit：转换倍数
       * @param yuan
       * @param digit
       * @returns {number}
       */
      regYuanToFen (yuan, digit) {
        var m = 0,
          s1 = yuan.toString(),
          s2 = digit.toString();
        try {
          m += s1.split(".")[1].length
        } catch (e) {
        }
        try {
          m += s2.split(".")[1].length
        } catch (e) {
        }
        return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
      },
      toDecimal2 (x) {
        var f = parseFloat(x)
        if (isNaN(f)) {
          return false
        }
        var f = Math.round(x * 100) / 100
        var s = f.toString()
        var rs = s.indexOf('.')
        if (rs < 0) {
          rs = s.length
          s += '.'
        }
        while (s.length <= rs + 2) {
          s += '0'
        }
        return s
      },
    }
  }
</script>
<style scoped="scoped">
  .text {
    font-size: 12px;
  }
  .item {
    margin-bottom: -20px;
  }
</style>
